// todoSlice.ts
import {createSlice, createAsyncThunk, PayloadAction} from '@reduxjs/toolkit';
import axios from 'axios';

export interface Todo {
  _id: string;
  task: string;
  state: 'todo' | 'pending' | 'done';
  startTime: string;
  endTime: string;
}

interface TodoState {
  items: Todo[];
  status: 'idle' | 'loading' | 'succeeded' | 'failed';
  error: string | null;
}

const initialState: TodoState = {
  items: [],
  status: 'idle',
  error: null,
};

const API_BASE = 'http://mine.mikis.space:4569';
// 或者运行本地服务器 const API_BASE = 'http://localhost:3000';
export const fetchTodos = createAsyncThunk('todos/fetchTodos', async () => {
  console.log('fetchTodos');
  axios.get('http://mine.mikis.space:4569/todo')
  .then(res => console.log(res.data))
  .catch(err => console.log(err));
  const response = await axios.get<Todo[]>(`${API_BASE}/todo`);
  console.log('response', response);
  return response.data;
});

export const addTodo = createAsyncThunk(
  'todos/addTodo',
  async (todo: Omit<Todo, '_id'>) => {
    const response = await axios.post<Todo>(`${API_BASE}/todo`, todo);
    return response.data;
  },
);

export const deleteTodo = createAsyncThunk(
  'todos/deleteTodo',
  async (id: string) => {
    await axios.delete(`${API_BASE}/todo/${id}`);
    return id;
  },
);

export const updateTodoState = createAsyncThunk(
  'todos/updateTodoState',
  async ({id, state}: {id: string; state: 'todo' | 'pending' | 'done'}) => {
    const response = await axios.patch<Todo>(`${API_BASE}/todo/${id}`, {state});
    return response.data;
  },
);

const todoSlice = createSlice({
  name: 'todos',
  initialState,
  reducers: {
    // 乐观添加
    optimisticAddTodo: (state, action: PayloadAction<Todo>) => {
      state.items.push(action.payload);
    },
    // 乐观状态更新
    optimisticUpdateTodoState: (
      state,
      action: PayloadAction<{id: string; state: 'todo' | 'pending' | 'done'}>,
    ) => {
      const todo = state.items.find(item => item._id === action.payload.id);
      if (todo) {
        todo.state = action.payload.state;
      }
    },
  },
  extraReducers: builder => {
    builder
      .addCase(fetchTodos.pending, state => {
        state.status = 'loading';
      })
      .addCase(fetchTodos.fulfilled, (state, action: PayloadAction<Todo[]>) => {
        console.log('action.payload', action.payload);
        state.status = 'succeeded';
        state.items = action.payload;
      })
      .addCase(fetchTodos.rejected, (state, action) => {
        state.status = 'failed';
        state.error = action.error.message || null;
      })

      .addCase(addTodo.fulfilled, (state, action: PayloadAction<Todo>) => {
        // 找到临时 ID 的项
        // 乐观更新的ID 要更新为真实的ID
        const tempIndex = state.items.findIndex(
          item => item.task === action.payload.task && item.startTime === action.payload.startTime,
        ); // uuid 形式的临时 ID

        if (tempIndex !== -1) {
          // 替换临时 todo 为服务器返回的 todo（含真实 ID）
          state.items[tempIndex] = action.payload;
        } else {
          // 如果找不到临时的，直接添加
          state.items.push(action.payload);
        }
      })

      .addCase(deleteTodo.fulfilled, (state, action: PayloadAction<string>) => {
        state.items = state.items.filter(todo => todo._id !== action.payload);
      })

      .addCase(
        updateTodoState.fulfilled,
        (state, action: PayloadAction<Todo>) => {
          const index = state.items.findIndex(
            todo => todo._id === action.payload._id,
          );
          if (index !== -1) {
            state.items[index] = action.payload;
          }
        },
      );
  },
});
export const {optimisticAddTodo, optimisticUpdateTodoState} = todoSlice.actions;

export default todoSlice.reducer;
